package com.example.mydy;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mydy.adapter.RewardAdapter;
import com.example.mydy.model.RewardTask;
import com.example.mydy.model.UserData;
import com.example.mydy.utils.MockDataManager;
import com.example.mydy.utils.SharedPreferencesManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class RewardActivity extends AppCompatActivity implements RewardAdapter.OnRewardClickListener {
    private static final String TAG = "RewardActivity";

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView rvRewards;
    private TextView tvNoRewards;
    private TextView tvCategoryTitle;
    private EditText etSearchRewards;
    private TextView tvUserBalance;
    private TextView tvTodayIncome;
    private TextView tvTotalIncome;
    private TextView tvCompleteCount;
    
    private RewardAdapter rewardAdapter;
    private List<RewardTask> allRewardTasks = new ArrayList<>();
    private List<RewardTask> filteredRewardTasks = new ArrayList<>();
    
    private String username;
    private String currentCategory = "all"; // all, new, hot, taken, completed
    private Button btnCategoryAll, btnCategoryNew, btnCategoryHot, btnCategoryTaken, btnCategoryCompleted;
    private DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reward);
        
        username = SharedPreferencesManager.getUsername(this);
        
        initViews();
        setupToolbar();
        setupBottomNavigation();
        setupCategoryButtons();
        setupRecyclerView();
        setupListeners();
        loadData();
    }
    
    private void initViews() {
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
        rvRewards = findViewById(R.id.rv_rewards);
        tvNoRewards = findViewById(R.id.tv_no_rewards);
        tvCategoryTitle = findViewById(R.id.tv_category_title);
        etSearchRewards = findViewById(R.id.et_search_rewards);
        tvUserBalance = findViewById(R.id.tv_user_balance);
        tvTodayIncome = findViewById(R.id.tv_today_income);
        tvTotalIncome = findViewById(R.id.tv_total_income);
        tvCompleteCount = findViewById(R.id.tv_complete_count);
        
        btnCategoryAll = findViewById(R.id.btn_category_all);
        btnCategoryNew = findViewById(R.id.btn_category_new);
        btnCategoryHot = findViewById(R.id.btn_category_hot);
        btnCategoryTaken = findViewById(R.id.btn_category_taken);
        btnCategoryCompleted = findViewById(R.id.btn_category_completed);
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
            }

            @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 仅管理员可见添加按钮
        if (SharedPreferencesManager.isAdmin(this)) {
            getMenuInflater().inflate(R.menu.menu_reward, menu);
        }
        return true;
            }

            @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_add_reward) {
            showAddRewardDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    private void setupBottomNavigation() {
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        // 设置当前选中项
        bottomNavigationView.setSelectedItemId(R.id.nav_reward);
        
        // 设置导航菜单项选择监听器
        bottomNavigationView.setOnItemSelectedListener(item -> {
            if (item.getItemId() == R.id.nav_home) {
                startActivity(new Intent(this, MainActivity.class));
                finish();
                return true;
            } else if (item.getItemId() == R.id.nav_advertisement) {
                startActivity(new Intent(this, AdvertisementListActivity.class));
                finish();
                return true;
            } else if (item.getItemId() == R.id.nav_project) {
                startActivity(new Intent(this, ProjectActivity.class));
                finish();
                return true;
            } else if (item.getItemId() == R.id.nav_reward) {
                // 当前已经在悬赏页面
                return true;
            } else if (item.getItemId() == R.id.nav_my) {
                startActivity(new Intent(this, MyActivity.class));
                finish();
                return true;
            }
            return false;
        });
    }
    
    private void setupCategoryButtons() {
        // 设置全部分类按钮点击事件
        btnCategoryAll.setOnClickListener(v -> {
            currentCategory = "all";
            tvCategoryTitle.setText("全部任务");
            updateCategoryButtons();
            filterTasks(etSearchRewards.getText().toString());
        });
        
        // 设置最新分类按钮点击事件
        btnCategoryNew.setOnClickListener(v -> {
            currentCategory = "new";
            tvCategoryTitle.setText("最新任务");
            updateCategoryButtons();
            filterTasks(etSearchRewards.getText().toString());
        });
        
        // 设置热门分类按钮点击事件
        btnCategoryHot.setOnClickListener(v -> {
            currentCategory = "hot";
            tvCategoryTitle.setText("热门任务");
            updateCategoryButtons();
            filterTasks(etSearchRewards.getText().toString());
        });
        
        // 设置已接取分类按钮点击事件
        btnCategoryTaken.setOnClickListener(v -> {
            currentCategory = "taken";
            tvCategoryTitle.setText("我的进行中任务");
            updateCategoryButtons();
            filterTasks(etSearchRewards.getText().toString());
        });
        
        // 设置已完成分类按钮点击事件
        btnCategoryCompleted.setOnClickListener(v -> {
            currentCategory = "completed";
            tvCategoryTitle.setText("我的已完成任务");
            updateCategoryButtons();
            filterTasks(etSearchRewards.getText().toString());
        });
        
        // 初始状态下选中"全部"
        updateCategoryButtons();
    }
    
    private void updateCategoryButtons() {
        // 重置所有按钮样式
        btnCategoryAll.setSelected(false);
        btnCategoryNew.setSelected(false);
        btnCategoryHot.setSelected(false);
        btnCategoryTaken.setSelected(false);
        btnCategoryCompleted.setSelected(false);
        
        // 设置当前选中按钮样式
        switch (currentCategory) {
            case "all":
                btnCategoryAll.setSelected(true);
                break;
            case "new":
                btnCategoryNew.setSelected(true);
                break;
            case "hot":
                btnCategoryHot.setSelected(true);
                break;
            case "taken":
                btnCategoryTaken.setSelected(true);
                break;
            case "completed":
                btnCategoryCompleted.setSelected(true);
                break;
        }
    }
    
    private void setupRecyclerView() {
        rewardAdapter = new RewardAdapter(filteredRewardTasks, this);
        rvRewards.setLayoutManager(new LinearLayoutManager(this));
        rvRewards.setAdapter(rewardAdapter);
    }
    
    private void setupListeners() {
        swipeRefreshLayout.setOnRefreshListener(this::loadData);
        
        etSearchRewards.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            
            @Override
            public void afterTextChanged(Editable s) {
                filterTasks(s.toString());
            }
        });
    }
    
    private void loadData() {
        swipeRefreshLayout.setRefreshing(true);
        loadUserData();
        loadRewardTasks();
    }
    
    private void loadUserData() {
        if (username == null || username.isEmpty()) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            swipeRefreshLayout.setRefreshing(false);
            return;
        }
        
        // 从MockDataManager获取用户数据
        UserData userData = MockDataManager.getUserDataStatic(username);
        if (userData != null) {
            updateUserData(userData);
        } else {
            Toast.makeText(this, "获取用户数据失败", Toast.LENGTH_SHORT).show();
        }
        
        swipeRefreshLayout.setRefreshing(false);
    }
    
    private void updateUserData(UserData userData) {
        tvUserBalance.setText(String.format("¥ %.2f", userData.getBalance()));
        tvTodayIncome.setText(String.format("%.2f", userData.getTodayIncome()));
        tvTotalIncome.setText(String.format("%.2f", userData.getTotalIncome()));
        tvCompleteCount.setText(String.valueOf(userData.getCompletedTaskCount()));
    }
    
    private void loadRewardTasks() {
        if (username == null || username.isEmpty()) {
            swipeRefreshLayout.setRefreshing(false);
            return;
        }
        
        // 从MockDataManager获取所有悬赏任务
        allRewardTasks.clear();
        allRewardTasks.addAll(MockDataManager.getAllRewardTasksStatic());
        
        // 过滤和排序任务
        filterTasks(etSearchRewards.getText().toString());
                    swipeRefreshLayout.setRefreshing(false);
    }
    
    private void filterTasks(String query) {
        filteredRewardTasks.clear();
        
        // 根据搜索词和当前分类过滤任务
        for (RewardTask task : allRewardTasks) {
            // 按分类过滤
            boolean matchesCategory;
            switch (currentCategory) {
                case "new":
                    matchesCategory = task.isNew();
                    break;
                case "hot":
                    matchesCategory = task.isHot();
                    break;
                case "taken":
                    matchesCategory = username != null && 
                                     username.equals(task.getUsername()) && 
                                     !task.isCompleted();
                    break;
                case "completed":
                    matchesCategory = username != null && 
                                     username.equals(task.getUsername()) && 
                                     task.isCompleted();
                    break;
                case "all":
                default:
                    matchesCategory = true;
                    break;
            }
            
            // 按搜索词过滤
            boolean matchesQuery = query.isEmpty() ||
                    task.getTitle().toLowerCase().contains(query.toLowerCase()) ||
                    task.getDescription().toLowerCase().contains(query.toLowerCase());
            
            if (matchesCategory && matchesQuery) {
                filteredRewardTasks.add(task);
            }
        }
        
        // 更新适配器
        rewardAdapter.notifyDataSetChanged();
        
        // 更新提示文本可见性
        updateTasksVisibility();
    }
    
    private void updateTasksVisibility() {
        if (filteredRewardTasks.isEmpty()) {
            rvRewards.setVisibility(View.GONE);
            tvNoRewards.setVisibility(View.VISIBLE);
            
            // 根据当前分类显示不同的提示
            switch (currentCategory) {
                case "new":
                    tvNoRewards.setText("暂无最新悬赏任务");
                    break;
                case "hot":
                    tvNoRewards.setText("暂无热门悬赏任务");
                    break;
                case "taken":
                    tvNoRewards.setText("您暂未接取任何进行中的悬赏任务");
                    break;
                case "completed":
                    tvNoRewards.setText("您暂无已完成的悬赏任务");
                    break;
                case "all":
                default:
                    tvNoRewards.setText("暂无可接取的悬赏任务");
                    break;
            }
                    } else {
            rvRewards.setVisibility(View.VISIBLE);
            tvNoRewards.setVisibility(View.GONE);
                    }
                }
                
                @Override
    public void onRewardClick(RewardTask rewardTask) {
        // 是否已接取
        boolean isTaken = username != null && username.equals(rewardTask.getUsername());
        
        if (isTaken) {
            // 显示任务详情和提交界面
            showTaskSubmitDialog(rewardTask);
        } else {
            // 显示接取任务确认框
            showTaskTakeDialog(rewardTask);
        }
    }
    
                @Override
    public void onEditClick(RewardTask rewardTask) {
        // 这个功能仅对管理员开放
        boolean isAdmin = SharedPreferencesManager.isAdmin(this);
        if (isAdmin) {
            showEditRewardDialog(rewardTask);
                    }
                }
                
                @Override
    public void onDeleteClick(RewardTask rewardTask) {
        // 这个功能仅对管理员开放
        boolean isAdmin = SharedPreferencesManager.isAdmin(this);
        if (isAdmin) {
            new AlertDialog.Builder(this)
                    .setTitle("确认删除")
                    .setMessage("您确定要删除任务 " + rewardTask.getTitle() + " 吗？")
                    .setPositiveButton("确认", (dialog, which) -> {
                        boolean success = MockDataManager.deleteRewardTask(rewardTask.getId());
                        if (success) {
                            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                            loadRewardTasks();
                        } else {
                            Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }
    }
    
    private void showTaskTakeDialog(RewardTask rewardTask) {
        // 使用DialogFragment或AlertDialog显示接取任务确认框
        new AlertDialog.Builder(this)
                .setTitle("接取任务")
                .setMessage("您确定要接取任务: " + rewardTask.getTitle() + "\n奖励: ¥" + 
                        decimalFormat.format(rewardTask.getReward()) + "元吗?")
                .setPositiveButton("确定接取", (dialog, which) -> {
                    // 调用任务接取接口
                    boolean success = MockDataManager.takeRewardTask(username, rewardTask.getId());
                    if (success) {
                        Toast.makeText(this, "任务接取成功", Toast.LENGTH_SHORT).show();
                        // 刷新数据
                        loadRewardTasks();
                    } else {
                        Toast.makeText(this, "任务接取失败，可能已被他人接取", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void showTaskSubmitDialog(RewardTask rewardTask) {
        // 创建对话框视图
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_submit_reward, null);
        
        // 初始化对话框视图中的控件
        TextView tvTaskTitle = dialogView.findViewById(R.id.tv_task_title);
        TextView tvTaskDescription = dialogView.findViewById(R.id.tv_task_description);
        TextView tvTaskReward = dialogView.findViewById(R.id.tv_task_reward);
        TextView tvTaskStatus = dialogView.findViewById(R.id.tv_task_status);
        EditText etSubmissionContent = dialogView.findViewById(R.id.et_submission_content);
        Button btnSubmit = dialogView.findViewById(R.id.btn_submit);
        Button btnCancel = dialogView.findViewById(R.id.btn_cancel);
        
        // 设置任务信息
        tvTaskTitle.setText(rewardTask.getTitle());
        tvTaskDescription.setText(rewardTask.getDescription());
        tvTaskReward.setText("奖励: ¥" + decimalFormat.format(rewardTask.getReward()));
        
        // 设置任务状态
        switch (rewardTask.getProgressStatus()) {
            case RewardTask.STATUS_COMPLETED:
                tvTaskStatus.setText("状态: 已完成");
                tvTaskStatus.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
                btnSubmit.setEnabled(false);
                btnSubmit.setText("已完成");
                break;
            case RewardTask.STATUS_UNDER_REVIEW:
                tvTaskStatus.setText("状态: 审核中");
                tvTaskStatus.setTextColor(getResources().getColor(android.R.color.holo_orange_dark));
                btnSubmit.setEnabled(false);
                btnSubmit.setText("审核中");
                break;
            case RewardTask.STATUS_REJECTED:
                tvTaskStatus.setText("状态: 已拒绝");
                tvTaskStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                btnSubmit.setEnabled(true);
                btnSubmit.setText("重新提交");
                break;
            case RewardTask.STATUS_IN_PROGRESS:
            default:
                tvTaskStatus.setText("状态: 进行中");
                tvTaskStatus.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
                btnSubmit.setEnabled(true);
                btnSubmit.setText("提交任务");
                break;
        }
        
        // 如果已有提交内容，显示在输入框中
        if (rewardTask.getSubmissionContent() != null && !rewardTask.getSubmissionContent().isEmpty()) {
            etSubmissionContent.setText(rewardTask.getSubmissionContent());
        }
        
        // 创建对话框并设置视图
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(dialogView)
                .setCancelable(true)
                .create();
        
        // 设置提交按钮点击事件
        btnSubmit.setOnClickListener(v -> {
            String content = etSubmissionContent.getText().toString().trim();
            if (content.isEmpty()) {
                Toast.makeText(this, "请输入提交内容", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 更新任务状态为审核中
            rewardTask.setSubmissionContent(content);
            rewardTask.setSubmissionTime(dateFormat.format(new Date()));
            rewardTask.setProgressStatus(RewardTask.STATUS_UNDER_REVIEW);
            
            // 保存更新
            boolean success = MockDataManager.getInstance().updateRewardTask(rewardTask);
            if (success) {
                Toast.makeText(this, "提交成功，等待审核", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
                loadRewardTasks();
            } else {
                Toast.makeText(this, "提交失败，请稍后再试", Toast.LENGTH_SHORT).show();
            }
        });
        
        // 设置取消按钮点击事件
        btnCancel.setOnClickListener(v -> {
            // 判断是否是进行中状态，如果是，显示取消任务确认对话框
            if (rewardTask.getProgressStatus() == RewardTask.STATUS_IN_PROGRESS) {
                new AlertDialog.Builder(this)
                        .setTitle("确认取消")
                        .setMessage("您确定要放弃该任务吗?")
                        .setPositiveButton("确定放弃", (d, w) -> {
                            boolean success = MockDataManager.cancelRewardTask(username, rewardTask.getId());
                            if (success) {
                                Toast.makeText(this, "任务已取消", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                                loadRewardTasks();
                            } else {
                                Toast.makeText(this, "任务取消失败", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNegativeButton("继续任务", null)
                        .show();
            } else {
                // 如果不是进行中状态，直接关闭对话框
                dialog.dismiss();
            }
        });
        
        // 显示对话框
        dialog.show();
    }
    
    private void showAddRewardDialog() {
        // 创建对话框视图
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_reward, null);
        
        // 初始化对话框视图中的控件
        EditText etTitle = dialogView.findViewById(R.id.et_title);
        EditText etDescription = dialogView.findViewById(R.id.et_description);
        EditText etReward = dialogView.findViewById(R.id.et_reward);
        Button btnAdd = dialogView.findViewById(R.id.btn_add);
        Button btnCancel = dialogView.findViewById(R.id.btn_cancel);
        
        // 创建对话框并设置视图
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(dialogView)
                .setCancelable(true)
                .create();
        
        // 设置添加按钮点击事件
        btnAdd.setOnClickListener(v -> {
            String title = etTitle.getText().toString().trim();
            String description = etDescription.getText().toString().trim();
            String rewardStr = etReward.getText().toString().trim();
            
            if (title.isEmpty() || description.isEmpty() || rewardStr.isEmpty()) {
                Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }
            
            try {
                double reward = Double.parseDouble(rewardStr);
                if (reward <= 0) {
                    Toast.makeText(this, "奖励金额必须大于0", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                // 创建新任务
                RewardTask newTask = new RewardTask();
                // 简单地使用时间戳作为ID，实际应用中应该使用更合适的ID生成方式
                newTask.setId((int) (System.currentTimeMillis() % 10000));
                newTask.setTitle(title);
                newTask.setDescription(description);
                newTask.setReward(reward);
                newTask.setCreateTime(dateFormat.format(new Date()));
                newTask.setNew(true); // 默认为新任务
                
                // 保存任务
                boolean success = MockDataManager.addRewardTask(newTask);
                if (success) {
                    Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                    loadRewardTasks();
                } else {
                    Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show();
                }
            } catch (NumberFormatException e) {
                Toast.makeText(this, "奖励金额必须是有效数字", Toast.LENGTH_SHORT).show();
            }
        });
        
        // 设置取消按钮点击事件
        btnCancel.setOnClickListener(v -> dialog.dismiss());
        
        // 显示对话框
        dialog.show();
    }
    
    private void showEditRewardDialog(RewardTask rewardTask) {
        // 创建对话框视图
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_reward, null);
        
        // 初始化对话框视图中的控件
        EditText etTitle = dialogView.findViewById(R.id.et_title);
        EditText etDescription = dialogView.findViewById(R.id.et_description);
        EditText etReward = dialogView.findViewById(R.id.et_reward);
        Button btnAdd = dialogView.findViewById(R.id.btn_add);
        Button btnCancel = dialogView.findViewById(R.id.btn_cancel);
        
        // 设置现有值
        etTitle.setText(rewardTask.getTitle());
        etDescription.setText(rewardTask.getDescription());
        etReward.setText(String.valueOf(rewardTask.getReward()));
        btnAdd.setText("保存");
        
        // 创建对话框并设置视图
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("编辑悬赏任务")
                .setView(dialogView)
                .setCancelable(true)
                .create();
        
        // 设置保存按钮点击事件
        btnAdd.setOnClickListener(v -> {
            String title = etTitle.getText().toString().trim();
            String description = etDescription.getText().toString().trim();
            String rewardStr = etReward.getText().toString().trim();
            
            if (title.isEmpty() || description.isEmpty() || rewardStr.isEmpty()) {
                Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }
            
            try {
                double reward = Double.parseDouble(rewardStr);
                if (reward <= 0) {
                    Toast.makeText(this, "奖励金额必须大于0", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                // 更新任务信息
                rewardTask.setTitle(title);
                rewardTask.setDescription(description);
                rewardTask.setReward(reward);
                
                // 保存更新
                boolean success = MockDataManager.getInstance().updateRewardTask(rewardTask);
                if (success) {
                    Toast.makeText(this, "更新成功", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                    loadRewardTasks();
                } else {
                    Toast.makeText(this, "更新失败", Toast.LENGTH_SHORT).show();
                }
            } catch (NumberFormatException e) {
                Toast.makeText(this, "奖励金额必须是有效数字", Toast.LENGTH_SHORT).show();
            }
        });
        
        // 设置取消按钮点击事件
        btnCancel.setOnClickListener(v -> dialog.dismiss());
        
        // 显示对话框
        dialog.show();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }
}